﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using ctdReader;
namespace JsRunTool
{
    public class ThreadParamter
    {
        public ThreadParamter()
        {
            m_list = new List<string>();
        }
        public Form1 formArgs;      //可以加其它变量

        public string filePath;
        public string funName;
        public List<string> m_list; //dll-funname,js
        public string inData;
        public string outData;

        public CardDllInterface cardDll;
    }

    public class MyThread
    {
        private ThreadParamter threadParamter;
        private Thread thread;

        public MyThread(ThreadParamter _threadParamter)
        {
            threadParamter = _threadParamter;
            thread = new Thread(new ThreadStart(Run));
            thread.Name = "MyThread";
            Control.CheckForIllegalCrossThreadCalls = false;
            thread.IsBackground = true; 
        }

        public void Start()
        {
            if (thread != null)
            {
                thread.Start();
            }
        }

        public void Run()
        {
            try
            {
                int ret = 0;
                for (int i = 0; i < threadParamter.m_list.Count; i++)
                {
                    StringBuilder retBdstr = new StringBuilder(2048);
                    string filePath = threadParamter.m_list[0];

                    if (filePath.ToLower().Contains(".js"))
                    {
                        ret = CPublic.runJs(filePath, threadParamter.inData, retBdstr);
                    }
                    else
                    {
                        string[] dllPathFunName = filePath.Split(',');
                        ret = CPublic.checkCard(dllPathFunName[0], dllPathFunName[1], threadParamter.inData, retBdstr);
                    }

                    if (ret == 1)
                    {
                        threadParamter.outData += retBdstr.ToString();
                        threadParamter.formArgs.printRetData(threadParamter.outData);
                    }
                    else
                    {
                        threadParamter.outData += retBdstr.ToString();
                        threadParamter.formArgs.printRetData(threadParamter.outData);
                        break;
                    }
                }

                if (ret == 1)
                {
                    threadParamter.formArgs.printApdu("成功!");
                }
                else
                {
                    threadParamter.formArgs.printApdu("失败!");
                }
            }
            catch (System.Exception ex)
            {
                threadParamter.formArgs.printApdu("失败:" + ex.Message);
            }
        }
    }
}
